﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yule8xCommon.Applib;
using Yule8xCommon.Typelib;
using Yule8xModel;
using Yule8xWechat.Applib;

namespace Yule8xWechat.Qrcode
{
    public partial class GetUserQRCode : System.Web.UI.Page
    {
        bool useLocalImage = false; // 是否把二维码保存到本地
        bool isUseUnionID = false; // 二维码参数切换开关，true表示使用unionid,false表示使用id
        string promotion_tag; // 推广标识
        string unionid;
        int user_id;
        protected void Page_Load(object sender, EventArgs e)
        {
            user_id = RequestUtil.GetInteger("user_id");
            promotion_tag = RequestUtil.GetString("tag");
            if (string.IsNullOrEmpty(promotion_tag))
            {
                WxUserInfoResult wxUser;
                if (user_id > 0)
                {
                    wxUser = UserModels.GetWxUserInfo(user_id);
                    if (null == wxUser)
                    {
                        ResponseUtil.WriteEnd("user_id无效!");
                    }
                    unionid = wxUser.unionid;
                    user_id = wxUser.user_id;
                }
                else
                {
                    wxUser = LoginPageBase.GetLoginInfo();
                    if (null == wxUser)
                    {
                        Response.Write("登录超时");
                        Response.End();
                    }
                    unionid = wxUser.unionid;
                    user_id = wxUser.user_id;
                }
            }
            string dir = Server.MapPath("/Runtime/UserQrCode/");
            if (!Directory.Exists(dir))
            {
                try
                {
                    Directory.CreateDirectory(dir);
                }
                catch (Exception)
                {
                    throw;
                }
            }

            string filename = dir + (isUseUnionID ? unionid : user_id.ToString()) + ".png";
            if (useLocalImage && File.Exists(filename))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    System.Drawing.Image image = System.Drawing.Image.FromFile(filename);
                    image.Save(ms, ImageFormat.Png);
                    byte[] bytes = ms.ToArray();
                    Response.ClearContent();
                    Response.ContentType = "image/png";
                    Response.BinaryWrite(bytes);
                }
            }
            else
            {
                GetRemoteQrCode(filename, isUseUnionID, unionid, user_id);
            }
        }
        private void GetRemoteQrCode(string filename, bool isUseUnionID, string unionid, int uid)
        {
            // 初始化日志助手
            string errmsg;
            string token = WechatUtil.GetToken();
            LogUtil.Instance.WriteInfo("[获取微信推广二维码-GetRemoteQrCode] basetoken=" + token);
            // 获取推广二维码
            // 成功: {"ticket":"gQH47joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL2taZ2Z3TVRtNzJXV1Brb3ZhYmJJAAIEZ23sUwMEmm3sUw == ","expire_seconds":60,"url":"http:\/\/ weixin.qq.com\/ q\/ kZgfwMTm72WWPkovabbI"}
            // 场景值ID，临时二维码时为32位非0整型，永久二维码时最大值为100000（目前参数只支持1--100000）
            // 场景值ID（字符串形式的ID），字符串类型，长度限制为1到64，仅永久二维码支持此字段

            string tokenpost;
            if (!string.IsNullOrEmpty(promotion_tag))
            {
                tokenpost = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"tg:" + promotion_tag + "\"}}}";
            }
            else
            {
                if (isUseUnionID)
                {
                    tokenpost = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"" + unionid + "\"}}}";
                }
                else
                {
                    tokenpost = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": \"" + uid + "\"}}}";
                }
            }
            LogUtil.Instance.WriteInfo("[获取微信推广二维码-GetRemoteQrCode] tokenpost=" + tokenpost);
            string ewmurl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token;
            string ewmcontent = HttpUtil.HttpPost(ewmurl, tokenpost);
            LogUtil.Instance.WriteInfo("[获取微信推广二维码-GetRemoteQrCode] ewmcontent=" + ewmcontent);
            if (string.IsNullOrWhiteSpace(ewmcontent) || ewmcontent.IndexOf("errcode") > -1)
            {
                errmsg = "GetQrcodeTiket出错了：" + ewmcontent;
                LogUtil.Instance.WriteInfo("[获取微信推广二维码-GetRemoteQrCode] " + errmsg);
                Response.Write(errmsg);
                Response.End();
            }
            WxEwmTiketResult ewmtiket = JSON.parse<WxEwmTiketResult>(ewmcontent);
            // 通过ticket换取二维码
            // ticket正确情况下，http 返回码是200，是一张图片，可以直接展示或者下载。
            // 错误情况下（如ticket非法）返回HTTP错误码404。
            string tiketurl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + Server.UrlEncode(ewmtiket.ticket);
            LogUtil.Instance.WriteInfo("[获取微信推广二维码-GetRemoteQrCode] tiketurl=" + tiketurl);
            //string tiketcontent = HttpUtil.GetImage(tiketurl);
            byte[] bytes = HttpUtil.HttpGetBytes(tiketurl, "");
            if (useLocalImage)
            {
                Bitmap bmp = new Bitmap(new MemoryStream(bytes));
                bmp.Save(filename);
            }
            Response.ClearContent();
            Response.ContentType = "image/png";
            Response.BinaryWrite(bytes);
        }

    }
}